# File Name:
# Author:chenjiajun
# Date:2025/9/7

from . import db
from datetime import datetime
from sqlalchemy import text

class Server(db.Model):
    sev_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    sev_name = db.Column(db.String(100), nullable=False)
    sev_ip = db.Column(db.String(15), nullable=False)
    sev_port = db.Column(db.Integer, nullable=False)
    sev_status = db.Column(db.String(100), nullable=False, default='1')
    sev_remark = db.Column(db.String(500))
    add_time = db.Column(db.DateTime, default=datetime.now)

    @classmethod
    def create_server(cls, sev_name, sev_ip, sev_port, sev_remark, sev_status = 1):
        server = cls()
        server.sev_name = sev_name
        server.sev_ip = sev_ip
        server.sev_port = sev_port
        server.sev_remark = sev_remark
        server.sev_status = sev_status
        db.session.add(server)
        db.session.commit()

    @staticmethod
    def delete_server(id):
        server = Server.query.get(id)
        db.session.delete(server)
        db.session.commit()

    @staticmethod
    def modify_server(sev_id,sev_name, sev_ip, sev_port, sev_remark, sev_status):
        server = Server.query.get(sev_id)
        server.sev_name = sev_name
        server.sev_ip = sev_ip
        server.sev_port = sev_port
        server.sev_remark = sev_remark
        server.sev_status = sev_status
        db.session.add(server)
        db.session.commit()

    @staticmethod
    def select_server(keyword,status):
        sql1 = 'select * from server where 1=1'
        if keyword:
            sql1 += f" and (sev_name like '%{keyword}%' or sev_ip like '%{keyword}%' or sev_port like '%{keyword}%' or sev_remark like '%{keyword}%')"
        if status:
            sql1 += f' and sev_status = {status}'
        ret = db.session.execute(text(sql1)).fetchall()
        return ret

    @staticmethod
    def select_server_count(keyword,status):
        sql1 = 'select count(*) from server where 1=1'
        if keyword:
            sql1 += f" and (sev_name like '%{keyword}%' or sev_ip like '%{keyword}%' or sev_port like '%{keyword}%' or sev_remark like '%{keyword}%')"
        if status:
            sql1 += f' and sev_status = {status}'
        ret = db.session.execute(text(sql1)).fetchall()
        return ret


    def keys(self):
        return 'sev_id', 'sev_name', 'sev_ip', 'sev_port', 'sev_status', 'sev_remark', 'add_time'


    def __getitem__(self, key):
        if key == 'add_time':
            self.add_time = self.add_time.strftime("%Y-%m-%d %H:%M:%S")
            return self.add_time
        else:
            return getattr(self, key)